package com.jike.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jike.exception.UserNotFound;
import com.jike.model.User;
import com.jike.repository.UserRepository;
@Service("userService")
public class UserServiceImpl implements UserService {
	@Autowired
	private UserRepository userRepository;

	@Override
	public void add(User user) {
		userRepository.save(user);
	}

	@Override
	public User updateUser(User user) throws UserNotFound {
		User userUpdate = userRepository.findOne(user.getId());
		if (null == userUpdate)
			throw new UserNotFound();
		if (null != user.getName())
			userUpdate.setName(user.getName());
		if (null != user.getAddress())
			userUpdate.setAddress(user.getAddress());
		if (null != user.getPhone())
			userUpdate.setPhone(user.getPhone());
		userRepository.save(userUpdate);
		return userUpdate;
	}

	@Override
	public User deleteUser(User user) throws UserNotFound {
		User userDelete = userRepository.findOne(user.getId());
		if (null == userDelete)
			throw new UserNotFound();
		userRepository.delete(userDelete);
		return userDelete;
	}

	@Override
	public User getUser(User user) {
		return userRepository.findOne(user.getId());
	}

	@Override
	public List<User> getUsers() {
		return userRepository.findAll();
	}

}
